package com.dem.android.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.content.Context;
import android.os.Environment;
import android.util.Log;

public class ImageUtil {

	public static  String downloadFromUrl(Context context, String fileName, String urlFile) {
		String PATH = null;
		FileOutputStream fos = null;
		InputStream is = null;
		HttpURLConnection c = null;
		try {
			URL url = new URL(urlFile);
			c = (HttpURLConnection) url.openConnection();
			c.setRequestMethod("GET");
			c.setDoOutput(true);
			c.connect();

			String state = Environment.getExternalStorageState();
			File outputFile;

			if (Environment.MEDIA_MOUNTED.equals(state)) {
				PATH = Environment.getExternalStorageDirectory() + "/download/";
				Log.v("log_tag", "PATH: " + PATH);
				File file = new File(PATH);
				file.mkdirs();
				outputFile = new File(file, fileName);
			} else {
				File mydir = context.getDir("mydir", Context.MODE_PRIVATE);
				PATH = mydir.getAbsolutePath() + "/";
				outputFile = new File(mydir, fileName);
			}

			fos = new FileOutputStream(outputFile);

			is = c.getInputStream();

			byte[] buffer = new byte[1024];
			int len1 = 0;
			while ((len1 = is.read(buffer)) != -1) {
				fos.write(buffer, 0, len1);
			}
			// fos.close();
			// is.close();
		} catch (IOException e) {
			Log.d("log_tag", "Error: " + e);
		} finally {
			try {
				c.disconnect();
				fos.close();
				is.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		Log.v("PATH + fileName", PATH + fileName);

		return PATH + fileName;
	}

}
